package com.zb.frame.modules.common.controller;

import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.Producer;
import com.zb.frame.base.model.AuthUserInfo;
import com.zb.frame.base.model.R;
import com.zb.frame.base.utils.encrypt.SimpleHashUtil;
import com.zb.frame.modules.common.vo.RouterMenuVO;
import com.zb.frame.modules.monitor.enums.LogModule;
import com.zb.frame.modules.monitor.enums.LogType;
import com.zb.frame.modules.monitor.service.LogService;
import com.zb.frame.modules.sys.entity.User;
import com.zb.frame.modules.sys.service.MenuService;
import com.zb.frame.modules.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
public class CommonController extends AbstractController{

    @Autowired
    UserService userService;

    @Autowired
    MenuService menuService;

    @Autowired
    LogService logService;

    @Autowired
    private Producer CaptchaProducer;

    /**
     * 获取前端界面(侧边导航菜单)的权限菜单数据
     * @return
     */
    @GetMapping("/base/authMenu")
    public R getAuthMenu() {
        Map<String, Object> ret = new HashMap<>();
        AuthUserInfo userInfo = this.getUser();
        List<RouterMenuVO> menus = menuService.getUserMenuList(userInfo.getRole());
        Set<String> perms = userInfo.getPermission();
        ret.put("menus", menus);
        ret.put("perms", perms);
        return R.ok(ret);
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/base/userInfo")
    public R getUserInfo() {
        Long userId = this.getUserId();
        User user = userService.getById(userId);
        // 密码脱敏
        user.setUserPassword("");
        return R.ok(user);
    }

    /**
     * 修改用户信息
     * @param data
     * @return
     */
    @PutMapping("/base/userInfo")
    public R updateUserInfo(@RequestBody User data) {
        Long userId = this.getUserId();
        User user = userService.getById(userId);
        String oldValue = JSON.toJSONString(user);
        data.setUserName(user.getUserName()); // 账号不可修改
        User userNew = userService.updateUser(user, data);
        if (userNew == null)
            return R.error("用户修改信息失败！");
        String newValue = JSON.toJSONString(userNew);
        // 添加日志
        logService.addLog(LogModule.BASEMODULE, LogType.UPDATE, oldValue, newValue, String.valueOf(userId), userId, "修改用户账号[" + user.getUserName() + "]信息成功");
        return R.ok("用户修改信息成功！");
    }

    /**
     * 修改用户密码
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @PutMapping("/base/password")
    public R resetPassword(String oldPassword, String newPassword) {
        Long userId = this.getUserId();
        User user = userService.getById(userId);
        if (!user.getUserPassword().equals(SimpleHashUtil.encode(oldPassword))) {
            return R.error("用户修改密码失败，密码不正确！");
        }
        user.setUserPassword(SimpleHashUtil.encode(newPassword));
        return userService.updatePassword(user) ? R.ok("用户修改密码成功！") : R.error("用户修改密码失败！");
    }

    @GetMapping("/logout")
    public R logout() {
        return R.ok();
    }

    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //获取图片验证码
        String code = CaptchaProducer.createText();
        BufferedImage image = CaptchaProducer.createImage(code);
        ImageIO.write(image, "jpg", response.getOutputStream());
    }
}
